import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useApi } from '@/composables/useApi'
import { ElMessage } from 'element-plus'

interface UserInfo {
  id: number
  username: string
  email?: string
  real_name?: string
  avatar?: string
  last_login_at?: string
  last_login_ip?: string
}

export const useAuthStore = defineStore('auth', () => {
  const api = useApi()
  
  // 状态
  const token = ref<string | null>(localStorage.getItem('token'))
  const userInfo = ref<UserInfo | null>(null)
  const loading = ref(false)
  
  // 计算属性
  const isAuthenticated = computed(() => !!token.value)
  const isLoggedIn = computed(() => !!token.value && !!userInfo.value)
  
  // 登录
  const login = async (username: string, password: string) => {
    try {
      loading.value = true
      console.log('发送登录请求...')
      const response = await api.post('/auth/login', { username, password })
      console.log('登录响应:', response)
      console.log('响应数据结构:', JSON.stringify(response, null, 2))
      
      if (response.code === 200) {
        console.log('登录成功，设置用户信息...')
        console.log('Token数据:', response.data.token)
        console.log('用户信息数据:', response.data.user_info)
        
        token.value = response.data.token
        userInfo.value = response.data.user_info
        localStorage.setItem('token', response.data.token)
        
        console.log('Token已设置:', token.value)
        console.log('用户信息已设置:', userInfo.value)
        console.log('认证状态:', isAuthenticated.value)
        console.log('登录状态:', isLoggedIn.value)
        
        ElMessage.success('登录成功')
        return true
      } else {
        console.log('登录失败:', response.message)
        ElMessage.error(response.message || '登录失败')
        return false
      }
    } catch (error) {
      console.error('登录失败:', error)
      ElMessage.error('登录失败')
      return false
    } finally {
      loading.value = false
    }
  }
  
  // 登出
  const logout = async () => {
    try {
      if (token.value) {
        await api.post('/auth/logout')
      }
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      // 无论API调用是否成功，都清除本地状态
      token.value = null
      userInfo.value = null
      localStorage.removeItem('token')
      ElMessage.success('已退出登录')
    }
  }
  
  // 获取用户信息
  const fetchUserInfo = async () => {
    if (!token.value) return false
    
    try {
      const response = await api.get('/auth/profile')
      
      if (response.code === 200) {
        userInfo.value = response.data
        return true
      } else {
        // Token可能已过期
        logout()
        return false
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      logout()
      return false
    }
  }
  
  // 刷新Token
  const refreshToken = async () => {
    if (!token.value) return false
    
    try {
      const response = await api.post('/auth/refresh')
      
      if (response.code === 200) {
        token.value = response.data.token
        localStorage.setItem('token', response.data.token)
        return true
      } else {
        logout()
        return false
      }
    } catch (error) {
      console.error('刷新Token失败:', error)
      logout()
      return false
    }
  }
  
  // 初始化认证状态
  const initAuth = async () => {
    if (token.value) {
      return await fetchUserInfo()
    }
    return false
  }
  
  return {
    // 状态
    token,
    userInfo,
    loading,
    
    // 计算属性
    isAuthenticated,
    isLoggedIn,
    
    // 方法
    login,
    logout,
    fetchUserInfo,
    refreshToken,
    initAuth
  }
}) 